package com.mengshu.token.utils;

import com.mengshu.token.properties.TokenConfig;
import com.mengshu.token.properties.TokenProperties;
import lombok.Getter;
import org.springframework.util.StringUtils;

import java.util.LinkedHashMap;

/**
 * <p>
 *     Token配置工具类
 * </p>
 *
 * @author liuning
 * @date 3:26 下午 2022/2/13
 */
@Getter
public class TokenConfigUtils {

    private LinkedHashMap<String, TokenConfig> tokenConfigs = new LinkedHashMap<>();

    public final static String SPLIT = "!#";

    @Getter
    private boolean multiTokenConfig;

    public TokenConfigUtils(TokenProperties tokenProperties) {
        tokenConfigs.clear();
        tokenConfigs.putAll(tokenProperties.getMultiTokenConfig());
        this.multiTokenConfig = tokenProperties.isMultiTokenConfig();
    }

    public String getTokenString(String token, String platform) {
        String tk = platform == null ? getDefaultPlatform() : platform;
        return new StringBuffer(getTokenPrefix(tk)).append(SPLIT).append(token).toString();
    }

    public long getTimeout(String tokenString) {
        return getTokenConfig(getPlatform(tokenString)).getLongTimeout();
    }

    public TokenConfig getDefaultConfig() {
        return tokenConfigs.values().iterator().next();
    }

    public String getTokenPrefix(String platform) {
        final TokenConfig tokenConfig = getTokenConfig(platform);
        return StringUtils.hasText(tokenConfig.getPrefix()) ? tokenConfig.getPrefix() : platform;
    }

    private TokenConfig getTokenConfig(String platform) {
        String tk = platform == null ? getDefaultPlatform() : platform;
        return tokenConfigs.get(tk);
    }

    public String getPlatform(String tokenString) {
        final String prefix = tokenString.split(SPLIT)[0];
        for (String platform : tokenConfigs.keySet()) {
            if (prefix.equals(getTokenPrefix(platform))) {
                return platform;
            }
        }
        return null;
    }

    public String getDefaultPlatform() {
        return this.tokenConfigs.keySet().iterator().next();
    }
}
